package cn.nhic.web.controller;/**
 * Created by duweiping on 2024/9/4 1:25
 */

import cn.nhic.web.common.HtmlUtils;
import cn.nhic.web.constant.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 表单数据,读取表单数据，并输出。
 * 大家联系一下，我这里就不写了。
 * @author duweiping
 * @date 2024/9/4 1:25
 */
@WebServlet(urlPatterns = "/read_form_servlet")
public class FormServletReader extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(Constants.DOC_FORMAT_TYPE);

        StringBuilder builder = HtmlUtils.generateHtmlHead("form register");
        builder.append("<body>");

        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap != null && !parameterMap.isEmpty()) {
            params.put("<strong> http body key</strong>", "<strong>http body value</strong>");
            for (Constants.ParamsKeyEnum paramsKeyEnum : Constants.ParamsKeyEnum.values()) {
                String[] valueArray = parameterMap.getOrDefault(paramsKeyEnum.getParamKey(), new String[]{});
                if (valueArray == null || valueArray.length == 0) {
                    continue;
                }
                params.put(paramsKeyEnum.getParamKey(), String.join(",", valueArray));
            }
        }

        // 2. todo map to string
        if (!params.isEmpty()) {
            builder.append("<table>");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.append("<tr> <td>").append(entry.getKey()).append("</td><td>")
                        .append(entry.getValue()).append("</td>");
            }

            builder.append("</table>");

        }


        builder.append("</body>");
        builder.append("</html>");

        PrintWriter out = resp.getWriter();
        out.println(builder.toString());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
